var express = require('express');
var async = require('async');
var router = express.Router();
var Curd = require('../model/curd.js');
var activity = require('../model/activity.js');
var path = require('path');
var fs = require('fs');
var ticket = require('../utils/ticket.js');
var config = require(path.resolve(__dirname, '../../config.js'));
var request = require('request');

/* GET home page. */
router.get('/getInfo', function(req, res, next) {

    var place = new Curd()(require('../model/campPlace.js'));
    place.find({}, function(err, result) {
        if (err) {
            res.send(500, { message: err })
        } else {
            res.send(result);
        }
    });
});
router.get('/place/getInfoById', function(req, res, next) {
    var id = req.query.id;
    var place = new Curd()(require('../model/campPlace.js'));
    place.find({ _id: id }, function(err, result) {
        if (err) {
            res.send(500, { message: err })
        } else {
            res.send(result);
        }
    });
});
router.post('/place/setInfo', function(req, res, next) {
    var info = req.body;
    if (info.serverIds.length > 0) {
        var picdir = path.resolve(__dirname, "../lgcpublic/camp/upload");
        if (!fs.existsSync(picdir)) {
            fs.mkdirSync(picdir);
        }
        async.waterfall([
            function(__cb) {
                ticket.gettoken(config.appid, config.secret, function(token) {
                    __cb(null, token);
                });
            },
            function(tk, __cb) {
                async.mapSeries(info.serverIds, function(serverId, cb) {
                    //从微信服务器中根据serverid下载微信语音到指定的路径下
                    var _url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=' + tk + '&media_id=' + serverId;
                    request.get(_url).on('err', function(err) {
                        res.send(500, { message: err });
                    }).pipe(fs.createWriteStream(path.resolve(picdir, serverId + ".jpg")));
                    cb(null,config.url+'/camp/upload/'+serverId+'.jpg');
                }, function(err, result) {
                    if (err) {
                        console.log(err)
                    }
                    console.log(result);
                    info.picPaths = result;
                    __cb(null, info);
                });
            },
        ], function(err, result) {
            if (err) {
                console.log(err);
            } else {
                //do st.
                var place = new Curd()(require('../model/campPlace.js'));
                place.save(result, function(err) {
                    if (err) {
                        res.send(500, { message: err })
                    } else {
                        res.sendStatus(200);
                    }
                });
            }
        });

    }
});
router.get('/user/getInfoById', function(req, res, next) {
    var id = req.query.id;
    var wechat = new Curd()(require('../model/wechat.js'));
    wechat.findByOpenId(id, function(err, result) {
        if (err) {
            res.send(500, { message: err });
        } else {
            res.send(result);
        }
    });
});
router.get('/getInfoById', function(req, res, next) {
    var id = req.query.id;
    place.findById(id, function(err, result) {
        if (err) {
            res.send(500, { message: err });
        } else {
            res.send(result);
        }
    });
});
router.post('/setInfo', function(req, res, next) {
    var info = req.body;
    console.log("提交的信息：" + JSON.stringify(info));
    var pics = info.picPaths;

    var user = req.body;
    var scenery_path = __dirname + "../../src/resource/images/scenery";
    if (!fs.existsSync(scenery_path)) {
        fs.mkdirSync(scenery_path);
    }
    async.waterfall([
        function(cb) {
            ticket.gettoken(appid, secret, function(token) {
                cb(null, token);
            });
        },
        function(tk, cb) {
            async.mapSeries(pics, function(pic, cb) {
                //从微信服务器中根据serverid下载微信语音到指定的路径下
                var _url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=' + tk + '&media_id=' + pic;
                user.path = './audio/' + user.serverId + '.mp3';
                request.get(_url).on('err', function(err) {
                    res.send(500, { message: err });
                }).pipe(fs.createWriteStream(scenery_path + pic + ".mp3"));

            }, function(err, result) {
                if (err) {
                    console.log(err);
                }
                console.log(result);
            });
        },
    ], function(err, result) {
        if (err) {
            console.log(err);
        }
        //do st.
        place.save(info, function(err, result) {
            if (err) {
                res.send(500, { message: err })
            } else {
                res.sendStatus(200);
            }
        });
    });


});
router.post('/updateInfo', function(req, res, next) {
    var newinfo = req.body;
    console.log("新的信息：" + JSON.stringify(newinfo));
    place.update({ _id: newinfo._id }, newinfo, function(err, result) {
        if (err) {
            res.send(500, { message: err })
        } else {
            res.sendStatus(200);
        }
    });
});
router.get('/comment/getInfo', function(req, res, next) {
    var id = req.query.id;
    console.log("露营地ID：" + id);
    var comment = new Curd()(require('../model/comment.js'));
    comment.find({ campId: id }, function(err, result) {
        if (err) {
            res.send(500, { message: err });
        } else {
            res.send(result);
        }
    });
});

router.post('/comment/setInfo', function(req, res, next) {
    var info = req.body;
    console.log("提交的信息：" + JSON.stringify(info));
    var comment = new Curd()(require('../model/comment.js'));
    comment.save(info, function(err) {
        if (err) {
            res.send(500, { message: err })
        } else {
            res.sendStatus(200);
        }
    });
});
router.get('/activity/getInfo', function(req, res, next) {
    var info = {};
    var activity = new Curd()(require('../model/activity.js'));
    activity.find({}, function(err, result) {
        if (err) {
            res.send(500, { message: err });
        } else {
            res.send(result)
        }
    });

});
router.post('/activity/SetInfo', function(req, res, next) {
    var info = req.body;
    var activity = new Curd()(require('../model/activity.js'));
    activity.save(info, function(err, result) {
        if (err) {
            res.send(500, { message: err });
        } else {
            res.sendStatus(200);
        }
    });
});
//报名
router.post('/activity/signup', function(req, res, next) {
    var info = req.body;
    var member = info.member;
    async.waterfall([
        function(cb) {
            var activity = new Curd()(require('../model/activity.js'));
            activity.findById(info.activityId, function(err, result) {
                if (err) {
                    cb(new Error(err));
                } else {
                    result[0].members.push(member);
                    cb(null, result[0]);
                }
            });
        },
        function(newactivity, cb) {
            console.log(newactivity)
            activity.update({ _id: info.activityId }, { $set: newactivity }, function(err) {
                if (err) {
                    cb(new Error(err));
                } else {
                    cb(null, activity);
                }
            });
        }
    ], function(err, result) {
        if (err) {
            res.send(500, { message: err });
        } else {
            res.send(result);
        }
    });
});
module.exports = router;
